import re
import os
import pandas as pd
import datetime
import re
import openpyxl
from openpyxl import load_workbook, Workbook


def create_filename():
    now = datetime.datetime.now()
    filename = "result_" + now.strftime("%Y%m%d%H%M%S") + ".xlsx"
    filepath = os.path.join("output", filename)
    return filepath

def replace_comma_with_dot(text):
    return text.replace(',', '.')

def extract_numbers_from_text(text):
    numbers = re.findall(r'-?\d+.\d+|-?\d+', text)
    return float(numbers[0]) if numbers else None

def process_single_string(item):
    match = re.match(r'(-?[\d.]+)\s*([a-zA-Z]+)', item)
    if match:
        value = float(match.group(1))
        value = abs(value)
        unit = match.group(2)
        if unit.lower() == 'ms':
            value *= 1000
            # unit = 'us'
        # else:
            # unit = 'us'
        # return f'{round(value, 3)} {unit}'
        return round(value, 4)
    return None


def read_file_content(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        if len(lines) > 0:
            return lines[0].strip()
        else:
            return None

def get_txt_files_list(folder_path):
    files = os.listdir(folder_path)
    txt_files = [file for file in files if file.endswith('.txt')]
    return txt_files

def get_txt_files(folder_path):
    txt_files = get_txt_files_list(folder_path)
    result = {}
    for file in txt_files:
        file_name, _ = os.path.splitext(file)
        file_path = os.path.join(folder_path, file)
        content = read_file_content(file_path)
        content = replace_comma_with_dot(content)
        result[file_name] = content
    return result

def get_first_letter(string):
    first_letter = string[0]
    return first_letter


def write_to_excel_in_specific_way(data, output_file, sheet_name):
    wb = load_workbook(output_file)
    sheet = wb[sheet_name]

    def write_data(row_i, column, value):
        font_color = "0000FF"
        cell = sheet.cell(row=row_i + 2, column=column)
        cell.value = value
        cell.font = openpyxl.styles.Font(color=font_color)

    cell_values = ['Avg', 'Max', 'Tim']

    first_letter = 1
    row_i = 0
    # 写入数据
    for i, filename in enumerate(data['File Name']):
        row_i += 1
        if first_letter != int(get_first_letter(filename)):
            first_letter = int(get_first_letter(filename))
            row_i += 1

        for j, cell_value in enumerate(cell_values):
            write_data(row_i, 4+j, data[cell_value][i])


    
    # 保存修改后的Excel文件
    wb.save(output_file)
    # 关闭Excel文件
    wb.close()

def write_to_excel(data, destination_file):
    # 创建一个新的工作簿
    if not os.path.exists(destination_file):
        workbook = Workbook()
    else:
        workbook = load_workbook(destination_file)
    # 获取默认的工作表
    sheet = workbook.active

    # 写入表头
    # sheet.cell(row=1, column=2, value='FileName')
    # sheet.cell(row=1, column=3, value='min')
    # sheet.cell(row=1, column=4, value='avg')
    # sheet.cell(row=1, column=5, value='max')
    # sheet.cell(row=1, column=6, value='time')

    first_num = 1
    row_i = 0
    # 写入数据
    for i, filename in enumerate(data['File Name']):
        row_i += 1
        if first_num != int(get_first_letter(filename)):
            first_num = int(get_first_letter(filename))
            row_i += 1
        # sheet.cell(row=row_i+2, column=2, value=filename)
        # sheet.cell(row=row_i+2, column=3, value=data['Min'][i])
        sheet.cell(row=row_i+2, column=4, value=data['Avg'][i])
        sheet.cell(row=row_i+2, column=5, value=data['Max'][i])
        sheet.cell(row=row_i+2, column=6, value=data['Tim'][i])

        # 调整列宽
        # sheet.column_dimensions['A'].width = 5
        # sheet.column_dimensions['B'].width = 20
        # sheet.column_dimensions['C'].width = 15
        # sheet.column_dimensions['D'].width = 10
        # sheet.column_dimensions['E'].width = 15
        # sheet.column_dimensions['F'].width = 15

    # 保存工作簿
    workbook.save(destination_file)


